#include <iostream>
#include <memory>
#include <unistd.h>

#include "TcpServer.hpp"
#include "Calculate.hpp"
#include "Protocol.hpp"

using namespace Protocol;
std::string HandlerRequest(std::string &inbuffer, bool *error_code)
{
  *error_code = true;
  // 计算器
  Calculate calculate;

  // 1.构建响应对象
  std::unique_ptr<Factory> factory(new Factory());
  auto req = factory->BuildRequest();
  
  // 2.读取序列化
  std::string message;
  std::string total_send_message;
  while (Decode(inbuffer, &message))
  {
    // 3.读到完整的报文，解包
    if (!req->DeSerialize(message))
    {
      std::cout << "DeSerialize Error" << std::endl;
      *error_code = false;
      return std::string();
    }

    //4.业务处理
    auto resp=calculate.Cal(req);
    
    //5.序列化
    std::string send_string;
    resp->Serialize(&send_string);
    
    send_string=Encode(send_string);
    
    //6.发送
    total_send_message+=send_string;
  }
  return total_send_message;
}

int main(int argc, char *argv[])
{
  if (argc != 2)
  {
    std::cout << "Usage:" << argv[0] << "port" << std::endl;
    return 0;
  }
  uint16_t serverport = std::stoi(argv[1]);

  std::unique_ptr<TcpServer> svr(new TcpServer(serverport, HandlerRequest));
  svr->Loop();
  return 0;
}
